<?php

namespace App\Http\Controllers\Admin;

use App\Models\Transition;
use App\Models\UserLevel;
use Illuminate\Http\Request;
use App\Models\User as UserModel;
use Illuminate\Support\Facades\Hash;

/**
 * @group 后台接口文档
 * @title 用户管理模块接口
 * @author chenke
 * @description 酒庄后台用户板块接口
 * @header name:X-Token type:string require:1 desc:登录令牌
 *  */
class User extends Base
{
    /**
     * @title 等级列表
     * @description 后台等级列表数据
     * @url /admin/user/levshow
     * @method GET
     * @module 等级板块
     * @author chenke
     * @param name:limit type:int require:1 default:1 other: desc:每页数据条数
     * @param name:page type:int require:1 default:1 other: desc:当前页数
     * @return code:错误码
     * @return message:错误提示
     * @return data:等级数据@
     * @data id:等级ID levelname:等级英文名称 levelname_zn:等级中文名称 min:等级最小值 max:等级最大值 cycle_rate:回馈钱包返现比例 integral:积分返赠比例
     */
    public function levList(Request $request){
        $data = $request->all();
        $limit = $data['limit'];
        $page = $data['page'];
        $searchCont = (isset($data['searchcontent']) && $data['searchcontent'])?$data['searchcontent']:'';
        $startDate = (isset($data['startDate']) && $data['startDate'])?$data['startDate']:'';
        $endDate = (isset($data['endDate']) && $data['endDate'])?$data['endDate']:'';
        $where = [];
        if($searchCont){
            $where[] = ['levename','like','%'.$searchCont.'%'];
        }
        $whereDates = [];
        if($endDate){
            $entime = strtotime($endDate) + 24*3600;
            $endDate = date('Y-m-d',$entime);
        }
        if($startDate && $endDate){
            $whereDates = [$startDate,$endDate];
        }
        $return = (new UserLevel())->getPageList(['limit'=>$limit,'page'=>$page],$where,$whereDates);
        return response()->json($return);
    }

    /**
     * @title 等级添加
     * @description 添加单个等级数据
     * @url /admin/user/crelev
     * @method POST
     * @module 等级板块
     * @author chenke
     * @param name:levelname type:string require:1 default: other: desc:等级英文名
     * @param name:levelname_zn type:string require:1 default: other: desc:等级中文名
     * @param name:min type:int require:1 default:0 other: desc:最低累计消费额度(分)
     * @param name:max type:int require:1 default:0 other: desc:最高累计消费额度(分)
     * @param name:cycle_rate type:int require:1 default:0 other: desc:回馈钱包比例
     * @param name:integral type:int require:1 default:0 other: desc:积分返赠比例
     * @return code:错误码
     * @return message:错误提示
     * @return data:正确返回时为空
     */
    public function levCreate(Request $request){
        $data = $request->post();
        $rules = [
            'levelname'=>'required|string',
            'levelname_zn'=>'required|string',
            'min'=>'required|integer',
            'max'=>'required|integer',
            'cycle_rate'=>'required|integer',
            'integral'=>'required|integer',
        ];

        $messages = [
            'levelname.required'=> '请填写等级英文名',
            'levelname_zn.required'=> '请填写等级中文名',
            'min.required'=> '请填写最低累计消费额度',
            'max.required'=> '请填写最高累计消费额度',
            'cycle_rate.required'=> '请填写回馈钱包比例',
            'integral.required'=> '请填写积分返赠比例',
            'min.integer'=> '最低累计消费额度必须是数值',
            'max.integer'=> '最高累计消费额度必须是数值',
            'cycle_rate.integer'=> '回馈钱包比例必须是数值',
            'integral.integer'=> '积分返赠比例必须是数值'
        ];
        try {
            $check = $this->checkParams($data,$rules,$messages);
            if($check['code']){
                return response()->json($check);
            }
            $data['created_at'] = date('Y-m-d H:i:s');
            $result =  (new  UserLevel())->insert($data);
            if($result){
                return response()->json([
                    'code'=>0,
                    'data'=>'',
                    'message'=>'添加成功'
                ]);
            }else{
                return response()->json([
                    'code'=>1,
                    'data'=>'',
                    'message'=>'添加失败,请重试'
                ]);
            }
        }catch (\Exception $e){
            $this->logErr($e->getCode(),$e->getMessage(),'levCreate');
            return response()->json([
                'code'=>1,
                'message'=>$e->getMessage()
            ]);
        }
    }

    /**
     * @title 等级编辑
     * @description 编辑单个等级数据
     * @url /admin/user/edtlev
     * @method POST
     * @module 等级板块
     * @author chenke
     * @param name:id type:int require:1 default: other: desc:等级ID
     * @param name:levelname type:string require:1 default: other: desc:等级英文名
     * @param name:levelname_zn type:string require:1 default: other: desc:等级中文名
     * @param name:min type:int require:1 default:0 other: desc:最低累计消费额度(分)
     * @param name:max type:int require:1 default:0 other: desc:最高累计消费额度(分)
     * @param name:cycle_rate type:int require:1 default:0 other: desc:回馈钱包比例
     * @param name:integral type:int require:1 default:0 other: desc:积分返赠比例
     * @return code:错误码
     * @return message:错误提示
     * @return data:正确返回时为空
     */
    public function levUpdate(Request $request){
        $data = $request->post();
        $rules = [
            'id'=>'required|integer',
            'levelname'=>'required|string',
            'levelname_zn'=>'required|string',
            'min'=>'required|integer',
            'max'=>'required|integer',
            'cycle_rate'=>'required|integer',
            'integral'=>'required|integer',
        ];

        $messages = [
            'id.required'=> '请选择等级',
            'id.integer'=> '等级参数不正确',
            'levelname.required'=> '请填写等级英文名',
            'levelname_zn.required'=> '请填写等级中文名',
            'min.required'=> '请填写最低累计消费额度',
            'max.required'=> '请填写最高累计消费额度',
            'cycle_rate.required'=> '请填写回馈钱包比例',
            'integral.required'=> '请填写积分返赠比例',
            'min.integer'=> '最低累计消费额度必须是数值',
            'max.integer'=> '最高累计消费额度必须是数值',
            'cycle_rate.integer'=> '回馈钱包比例必须是数值',
            'integral.integer'=> '积分返赠比例必须是数值'
        ];
        try {
            $check = $this->checkParams($data,$rules,$messages);
            if($check['code']){
                return response()->json($check);
            }
            $data['updated_at'] = date('Y-m-d H:i:s');
            $result =  (new UserLevel())->where('id',$data['id'])->update($data);
            if($result){
                return response()->json([
                    'code'=>0,
                    'data'=>'',
                    'message'=>'编辑成功'
                ]);
            }else{
                return response()->json([
                    'code'=>1,
                    'data'=>'',
                    'message'=>'编辑失败,请重试'
                ]);
            }
        }catch (\Exception $e){
            $this->logErr($e->getCode(),$e->getMessage(),'levCreate');
            return response()->json([
                'code'=>1,
                'message'=>$e->getMessage()
            ]);
        }
    }


    /**
     * @title 用户列表
     * @description 后台用户列表数据
     * @url /admin/user/usershow
     * @method GET
     * @module 用户板块
     * @author chenke
     * @param name:limit type:int require:1 default:1 other: desc:每页数据条数
     * @param name:page type:int require:1 default:1 other: desc:当前页数
     * @param name:searchcontent type:string require:0 default: other: desc:输入框搜索内容(对应电话号码)
     * @param name:searchlevel type:int require:0 default:0 other: desc:搜索等级
     * @param name:startDate type:date require:0 default: other: desc:搜索日期（开始日期）
     * @param name:endDate type:date require:0 default: other: desc:搜索日期（结束日期）
     * @return code:错误码
     * @return message:错误提示
     * @return data:等级数据@
     * @data id:等级ID email:用户邮箱 spreadid:用户推广ID username:用户英文名称 username_zn:用户中文名称 contact:联系方式 birthday:出生日期  total:累计消费总额 walletid:钱包ID created_at:注册时间 deleted_at:禁用时间
     */
    public function userList(Request $request){
        $data = $request->all();
        $limit = $data['limit'];
        $page = $data['page'];
        $searchCont = (isset($data['searchcontent']) && $data['searchcontent'])?$data['searchcontent']:'';
        $startDate = (isset($data['startDate']) && $data['startDate'])?$data['startDate']:'';
        $endDate = (isset($data['endDate']) && $data['endDate'])?$data['endDate']:'';
        $searchLevel = (isset($data['searchlevel']) && $data['searchlevel'])?$data['searchlevel']:0;
        $where = [];
        if($searchCont){
            $where[] = ['contact','like','%'.$searchCont.'%'];
        }
        if($searchLevel){
            $level = (new UserLevel())->where('id',$searchLevel)->select('min','max')->first();
            $where[] = ['total','>=',$level->min];
            $where[] = ['total','<',$level->max];
        }
        $whereDates = [];
        if($endDate){
            $entime = strtotime($endDate) + 24*3600;
            $endDate = date('Y-m-d',$entime);
        }
        if($startDate && $endDate){
            $whereDates = [$startDate,$endDate];
        }
        $return = (new UserModel())->getPageList(['limit'=>$limit,'page'=>$page],$where,$whereDates);
        return response()->json($return);
    }

    /**
     * @title 用户添加
     * @description 添加单个用户数据
     * @url /admin/user/creuser
     * @method POST
     * @module 用户板块
     * @author chenke
     * @param name:email type:string require:1 default: other: desc:用户邮箱（账号）
     * @param name:avator type:string require:1 default: other: desc:用户邮箱（账号）
     * @param name:username type:string require:1 default: other: desc:用户英文名
     * @param name:username_zn type:string require:1 default: other: desc:用户中文名
     * @param name:birthday type:date require:1 default: other: desc:用户生日
     * @param name:contact type:string require:1 default: other: desc:用户联系方式
     * @param name:total type:int require:1 default:0 other: desc:用户累计消费总额
     * @return code:错误码
     * @return message:错误提示
     * @return data: 用户ID
     */
    public function registerUser(Request $request){
        $data = $request->post();
        $rules = [
            'email'=>'required|unique:users|email',
            'username'=>'required|string',
            'avator'=>'required|string',
            'username_zn'=>'required|alpha_num',
            'contact'=>'required|string',
            'birthday'=>'required|date',
            'total'=>'required|integer'
        ];
        $messages = [
            'email.required'=> '请填写邮箱',
            'email.email'=> '请填写正确的邮箱地址',
            'email.unique'=> '该邮箱已注册',
            'contact.required'=> '请填写联系方式',
            'username.required'=> '请填写英文名',
            'avator.required'=> '请填上传头像',
            'username_zn.required'=> '请填写中文名',
            'birthday.required'=> '请填写生日',
            'birthday.date'=> '请选择正确的日期',
            'total.required'=> '请填写累计消费总额',
            'total.integer'=> '消费总额必须是数字'
        ];

        $check = $this->checkParams($data,$rules,$messages);
        if($check['code']){
            return response()->json($check);
        }
        $data['password'] = Hash::make('123456');
        $unid = uniqid();
        $data['spreadid'] = $unid.substr(date('ynjHis'),7,4) ;
        $data['token'] = $this->setToken($data['spreadid']);
        $result =  (new UserModel())->userAdd($data);
        if($result['code']){
            $this->logErr($result['code'],$result['message'],'registerUser');
        }
        return response()->json($result);
    }

    /**
     * @title 用户编辑
     * @description 编辑单个用户数据
     * @url /admin/user/edtuser
     * @method POST
     * @module 用户板块
     * @author chenke
     * @param name:id type:int require:1 default:0 other: desc:用户ID
     * @param name:email type:string require:1 default: other: desc:用户邮箱（账号）
     * @param name:username type:string require:1 default: other: desc:用户英文名
     * @param name:username_zn type:string require:1 default: other: desc:用户中文名
     * @param name:birthday type:date require:1 default: other: desc:用户生日
     * @param name:contact type:string require:1 default: other: desc:用户联系方式
     * @param name:total type:int require:1 default:0 other: desc:用户累计消费总额
     * @return code:错误码
     * @return message:错误提示
     * @return data:用户ID
     */
    public function userUpdate(Request $request){
        $data = $request->post();
        $rules = [
            'id'=>'required|integer',
            'email'=>'required|email',
            'avator'=>'required|string',
            'username'=>'required|string',
            'username_zn'=>'required|alpha_num',
            'contact'=>'required|string',
            'birthday'=>'required|date',
            'total'=>'required|integer'
        ];
        $messages = [
            'id.required'=> '用户ID不存在',
            'id.integer'=> '用户ID参数错误',
            'email.required'=> '请填写邮箱',
            'email.email'=> '请填写正确的邮箱地址',
            'email.unique'=> '该邮箱已注册',
            'avator.required'=> '请填上传头像',
            'contact.required'=> '请填写联系方式',
            'username.required'=> '请填写英文名',
            'username_zn.required'=> '请填写中文名',
            'total.required'=> '请填写累计消费总额',
            'total.integer'=> '消费总额必须是数字'
        ];

        $check = $this->checkParams($data,$rules,$messages);
        if($check['code']){
            return response()->json($check);
        }
        $result =  (new UserModel())->doUpdate($data);
        if($result['code']){
            $this->logErr($result['code'],$result['message'],'registerUser');
        }
        return response()->json($result);
    }

    /**
     * @title 用户状态改变
     * @description 用户启用/禁用 用户
     * @url /admin/user/userstatus
     * @method POST
     * @module 用户板块
     * @author chenke
     * @param name:id type:int require:1 default:0 other: desc:用户ID
     * @param name:status type:int require:1 default:0 other: desc:用户要变成的状态1为正常0为禁用
     * @return code:错误码
     * @return message:错误提示
     * @return data:用户ID
     */
    public function changeUser(Request $request){
        $data = $request->post();
        $rules = [
            'id'=>'required|integer',
            'status'=>'required|integer'
        ];
        $messages = [
            'id.required'=> '用户ID不存在',
            'id.integer'=> '用户ID参数错误',
            'status.required'=> '状态参数不存在',
            'status.integer'=> '状态参数错误',
        ];
        $check = $this->checkParams($data,$rules,$messages);
        if($check['code']){
            return response()->json($check);
        }
        $model = new UserModel();
        $result = $model->changeStatus($request->post());
        if($result['code']){
            $this->logErr($result['code'],$result['message'],'changeUser');
        }
        return response()->json($result);
    }

    /**
     * @title 用户充值
     * @description 后台给用户充值
     * @url /admin/user/recharge
     * @method POST
     * @module 用户板块
     * @author chenke
     * @param name:id type:int require:1 default:0 other: desc:用户ID
     * @param name:number type:int require:1 default:0 other: desc:充值金额
     * @return code:错误码
     * @return message:错误提示
     * @return data:成功时为空
     */
    public function rechargeUser(Request $request){
        $data = $request->post();
        $rules = [
            'id'=>'required|integer',
            'number'=>'required|integer'
        ];
        $messages = [
            'id.required'=> '用户ID不存在',
            'id.integer'=> '用户ID参数错误',
            'number.required'=> '请输入充值金额',
            'number.integer'=> '充值金额错误',
        ];
        $check = $this->checkParams($data,$rules,$messages);
        if($check['code']){
            return response()->json($check);
        }
        $data['transtatus'] =2;
        $data['evidence'] = '后台充值';
        $data['toname'] = "";
        $data['paybank'] = "";
        $data['bankcard'] = "";
        $result = (new Transition())->rechargeAdmin($data);
        if($result['code']){
            $this->logErr($result['code'],$result['message'],'rechargeUser');
        }
        return response()->json($result);
    }

    /**
     * @title 用户提现
     * @description 后台给用户提现
     * @url /admin/user/withdraw
     * @method POST
     * @module 用户板块
     * @author chenke
     * @param name:id type:int require:1 default:0 other: desc:用户ID
     * @param name:number type:int require:1 default:0 other: desc:提现金额
     * @return code:错误码
     * @return message:错误提示
     * @return data:成功时为空
     */
    public function withdrawUser(Request $request){
        $data = $request->post();
        $rules = [
            'id'=>'required|integer',
            'number'=>'required|integer'
        ];
        $messages = [
            'id.required'=> '用户ID不存在',
            'id.integer'=> '用户ID参数错误',
            'number.required'=> '请输入提现金额',
            'number.integer'=> '提现金额错误'
        ];
        $check = $this->checkParams($data,$rules,$messages);
        if($check['code']){
            return response()->json($check);
        }
        $data['transtatus'] = 2;
        $data['evidence'] = '后台提现';
        $result = (new Transition())->withDraw($data);
        if($result['code']){
            $this->logErr($result['code'],$result['message'],'rechargeUser');
        }
        return response()->json($result);
    }


    /**
     * @title 导出用户
     * @description 根据搜索条件导出所有符合条件的数据
     * @url /admin/user/excuser
     * @method POST
     * @module 用户板块
     * @author chenke
     * @param name:searchcontent type:string require:0 default: other: desc:输入框搜索内容
     * @param name:searchlevel type:int require:0 default:0 other: desc:搜索等级
     * @param name:startDate type:date require:0 default: other: desc:搜索日期（开始日期）
     * @param name:endDate type:date require:0 default: other: desc:搜索日期（结束日期）
     * @return code:错误码
     * @return message:错误提示
     * @return data:用户数据@
     * @data id:等级ID email:用户邮箱 spreadid:用户推广ID username:用户英文名称 username_zn:用户中文名称 contact:联系方式 birthday:出生日期  total:累计消费总额  created_at:注册时间 deleted_at:禁用时间
     */
    public function exportUser(Request $request){
        $data = $request->all();
        try{
            $searchCont = (isset($data['searchcontent']) && $data['searchcontent'])?$data['searchcontent']:'';
            $startDate = (isset($data['startDate']) && $data['startDate'])?$data['startDate']:'';
            $endDate = (isset($data['endDate']) && $data['endDate'])?$data['endDate']:'';
            $searchLevel = (isset($data['searchlevel']) && $data['searchlevel'])?$data['searchlevel']:0;
            $where = [];
            if($searchCont){
                $where[] = ['email','like','%'.$searchCont.'%'];
            }
            if($searchLevel){
                $level = (new UserLevel())->where('id',$searchLevel)->select('min','max')->first();
                $where[] = ['total','>=',$level->min];
                $where[] = ['total','<',$level->max];
            }
            $whereDates = [];
            if($endDate){
                $entime = strtotime($endDate) + 24*3600;
                $endDate = date('Y-m-d',$entime);
            }
            if($startDate && $endDate){
                $whereDates = [$startDate,$endDate];
            }
            $return = (new UserModel())->getAllList($where,$whereDates);
            return response()->json($return);
        }catch (\Exception $e){
            $this->logErr($e->getCode(),$e->getMessage(),'exportUser');
            return response()->json([
                'code'=>1,
                'message'=>'导出失败'
            ]);
        }

    }

    /**
     * @title 导入用户
     * @description 根据搜索条件导出所有符合条件的数据
     * @url /admin/user/impuser
     * @method POST
     * @module 用户板块
     * @author chenke
     * @param name:list type:array require:1 default:[] other: desc:需要导入的数据组(字段：email,username,username_zn,contact,birthday,total)
     * @return code:错误码
     * @return message:错误提示
     * @return data:导入失败的数据@
     * @data errmsg:导入失败原因 data:失败的数据
     */
    public function importUser(Request $request){
        $data = $request->post('list');
        $rules = [
            'email'=>'required|unique:users|email',
            'username'=>'required|string',
            'username_zn'=>'required|alpha_num',
            'contact'=>'required|string',
            'birthday'=>'required|date',
            'total'=>'required|integer'
        ];
        $messages = [
            'email.required'=> '请填写邮箱',
            'email.email'=> '请填写正确的邮箱地址',
            'email.unique'=> '该邮箱已注册',
            'contact.required'=> '请填写联系方式',
            'username.required'=> '请填写英文名',
            'username_zn.required'=> '请填写中文名',
            'birthday.required'=> '请填写生日',
            'birthday.date'=> '请选择正确的日期',
            'total.required'=> '请填写累计消费总额',
            'total.integer'=> '累计消费总额数值错误'
        ];
        $result =  (new UserModel())->userAddAll($data,$rules,$messages);
        if($result['code']){
            $this->logErr($result['code'],$result['message'],'importUser');
        }
        return response()->json($result);
    }

    /**
     * @title 登录密码修改
     * @description 更改用户登录密码
     * @url /admin/user/cagepass
     * @method POST
     * @module 用户板块
     * @author chenke
     * @param name:id type:int require:1 default: other: desc:用户ID
     * @param name:password type:string require:1 default: other: desc:新密码
     * @param name:password_confirmation type:string require:1 default: other: desc:确认密码
     * @return code:错误码
     * @return message:错误提示
     * @return data:成功时为空
     */
    public function changePassword(Request $request){
        $data = $request->post();
        $rules = [
            'id'=>'required|integer',
            'password'=>'required|confirmed',
            'password_confirmation'=>'required|same:password'
        ];
        $messages = [
            'id.required'=> '请传用户ID',
            'id.integer'=> '用户ID错误',
            'password.required'=> '请填写密码',
            'password.confirmed'=> '两次密码不一致',
            'password_confirmation.required'=> '请填写确认密码',
            'password_confirmation.same'=> '两次密码不一致'
        ];
        $check = $this->checkParams($data,$rules,$messages);
        if($check['code']){
            return response()->json($check);
        }
        $result =  (new UserModel())->passwordSet($data);
        if($result['code']){
            $this->logErr($result['code'],$result['message'],'changePassword');
        }
        return response()->json($result);
    }

    /**
     * @title 支付密码修改
     * @description 更改用户支付密码
     * @url /admin/user/cagepay
     * @method POST
     * @module 用户板块
     * @author chenke
     * @param name:id type:int require:1 default: other: desc:用户ID
     * @param name:password type:string require:1 default: other: desc:新密码
     * @param name:password_confirmation type:string require:1 default: other: desc:确认密码
     * @return code:错误码
     * @return message:错误提示
     * @return data:成功时为空
     */
    public function changePayPass(Request $request){
        $data = $request->post();
        $rules = [
            'id'=>'required|integer',
            'password'=>'required|confirmed',
            'password_confirmation'=>'required|same:password'
        ];
        $messages = [
            'id.required'=> '请传用户ID',
            'id.integer'=> '用户ID错误',
            'password.required'=> '请填写密码',
            'password.confirmed'=> '两次密码不一致',
            'password_confirmation.required'=> '请填写确认密码',
            'password_confirmation.same'=> '两次密码不一致'
        ];
        $check = $this->checkParams($data,$rules,$messages);
        if($check['code']){
            return response()->json($check);
        }
        $result =  (new UserModel())->payPassSet($data);
        if($result['code']){
            $this->logErr($result['code'],$result['message'],'changePayPass');
        }
        return response()->json($result);
    }
}
